import React, { useEffect, useState, useMemo, useCallback } from 'react';
import { Space, Button, Table, Modal, Form, Input, notification } from 'antd';

import {
  listAllByBuildingID,
  areaUpdate,
  areaAdd,
  areaDel,
} from './setServers';
import styles from '@/assets/setting/BuildSet.less';

/* 编辑框 */
const EditModal = (props: any) => {
  const { modalVisible, modalData, modalOnCancel, modalUpdata } = props;
  console.log('modal props 中的一些数据', props);

  const [modalForm] = Form.useForm();

  //
  const modalHandleOk = useCallback(() => {
    modalForm.validateFields().then((val: any) => {
      console.log('获取modal的值', modalData, val);
      delete modalData['uid'];
      if (modalUpdata({ ...modalData, buildingid: '', ...val })) {
        modalForm.resetFields();
      }
    });
  }, []);

  return (
    <Modal
      title={modalData['type'] === 'ADD' ? modalData['title'] : '编辑'}
      forceRender={false}
      maskClosable={false}
      visible={modalVisible}
      onOk={modalHandleOk}
      onCancel={modalOnCancel}
    >
      <Form
        name="modalForm"
        form={modalForm}
        labelCol={{ span: 4 }}
        autoComplete="off"
        initialValues={{
          name: modalData['NAME'],
          remark: modalData['REMARK'],
          ...modalData,
        }}
      >
        <Form.Item
          name="name"
          label="区域名称"
          rules={[{ required: true, message: '请填写区域名称！' }]}
        >
          <Input placeholder="请编辑区域名称" />
        </Form.Item>
        <Form.Item
          name="remark"
          label="备注"
          rules={[{ required: true, message: '请填写备注！' }]}
        >
          <Input placeholder="请编辑备注" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

/* 主程序 */
function AreaMtnSet(props: any) {
  const { history, match, location } = props;
  console.log('location !!!', history, location, match);
  if (!match.params.buildingId) {
    // history.goBack()
    history.go(-1);
    // history.push('/buildSet')
  }

  const [dataSource, setDataSource] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalData, setModalData] = useState({});

  const getListAllByBuildID = () => {
    listAllByBuildingID({ buildingId: match.params.buildingId }).then((res) => {
      console.log('建物区域资讯设定数据', res);
      res['data'].length &&
        res['data'].forEach((item: any, i: number) => {
          item['uid'] = item['ID'] + i;
        });
      setDataSource(res['data']);
    });
  };

  const columns = [
    {
      title: '区域名称',
      dataIndex: 'NAME',
      key: 'NAME',
    },
    {
      title: '备注',
      dataIndex: 'REMARK',
      key: 'REMARK',
    },
    {
      title: '处理',
      dataIndex: 'setting',
      key: 'setting',
      width: 200,
      render: (text: string, record: any) => {
        return (
          <Space>
            <Button
              size="small"
              type="primary"
              onClick={() => {
                setModalData(record);
                setModalVisible(true);
              }}
            >
              编辑
            </Button>
            <Button
              size="small"
              type="primary"
              danger
              onClick={() => {
                console.log('record', record);
                areaDel({
                  buildingid: record['BUILDINGID'],
                  id: record['ID'],
                })
                  .then((res) => {
                    notification.success({
                      message: '删除结果！',
                      description: res.message || '删除成功！',
                    });
                    getListAllByBuildID();
                  })
                  .catch((rej) => {
                    notification.error({
                      message: '删除结果！',
                      description: rej.message || '删除失败！',
                    });
                  });
              }}
            >
              删除
            </Button>
          </Space>
        );
      },
    },
  ];

  /* 数据更新或上传 */
  const modalUpdata = (val: any): boolean => {
    let success = true;
    if (val.type === 'ADD') {
      areaAdd({ ...val, buildingid: location.state.id }).then((res) => {
        console.log('添加 ADD 的数据 是否成功', val, res);
        getListAllByBuildID();
        setModalVisible(false);
      });
    } else {
      areaUpdate({ ...val, id: val['ID'], buildingid: location.state.id })
        .then((res) => {
          console.log('数据上传是否成功！', res);
          notification.success({
            message: '数据更新',
            description: res.message || res.msg || '数据更新成功',
          });
          setModalVisible(false);
          getListAllByBuildID();
        })
        .catch((rej) => {
          success = false;
          notification.error({
            message: '数据更新',
            description: rej.message || rej.msg || '数据更新失败',
          });
        });
    }

    return success;
  };
  const editModal = useMemo(() => {
    return (
      <EditModal
        key={modalVisible}
        modalVisible={modalVisible}
        modalData={modalData}
        modalOnCancel={() => {
          setModalVisible(false);
        }}
        modalUpdata={modalUpdata}
      />
    );
  }, [modalVisible, modalData]);

  useEffect(() => {
    getListAllByBuildID();
  }, []);

  return (
    <div className={styles['areaMtnSet__wrapper']}>
      <h2>建物区域资讯设定</h2>
      <Space>
        <p className={styles['am__Title__wrapper']}>
          <span>区域：</span>
          <span>{location.state ? location.state.ename : ''}</span>
          <span>建物名称：</span>
          <span>{location.state ? location.state.name : ''}</span>
        </p>
        <Button
          onClick={() => {
            setModalData({
              type: 'ADD',
              title: '新增',
            });
            setModalVisible(true);
          }}
        >
          新增
        </Button>
        <Button
          type="primary"
          onClick={() => {
            history.go(-1);
          }}
        >
          返回建物设定页面
        </Button>
      </Space>

      <Table
        rowKey={(record: any): string => {
          return record['uid'] || Math.random().toString(16);
        }}
        bordered
        size="middle"
        dataSource={dataSource}
        columns={columns}
        pagination={false}
      />
      {editModal}
    </div>
  );
}

export default AreaMtnSet;
